<template>
  <div class="wrapper">
    <h2 class="Title">todos</h2>
    <div class="todo-list">
      <input
        class="Input"
        v-model="newItem"
        @keyup.enter="addItem"
        type="text"
        placeholder="你接下来要做什么？"/>
      <ul v-if="items.length > 0">
        <li v-for="item in items" :key="item.id"  n>
          <input v-model="item.status" type="checkbox"/>
          <span :class="{ completed: item.status }">{{ item.text }}</span>
        </li>
      </ul>
      <p v-else>这里空空如也</p>
      <p v-if="incompleteItem > 0  || completeItem > 0">已完成{{ incompleteItem }}项</p>
      <p v-if="incompleteItem > 0 || completeItem > 0">待完成{{ completeItem }}项</p>
      <button v-if="incompleteItem > 0 || completeItem > 0" @click="clearCompleted">清除已完成</button>
      <button>全选</button>

    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'


 
// 定义变量newItem，用于存储用户输入的待办事项
// 定义变量items，用于存储待办项列表
const newItem = ref('')
const items = ref([])

// 添加待办事项
const addItem = () => {
  if (newItem.value.trim()) {
    const item = {
      id: Date.now(),
      text: newItem.value,
      status: false
    }
    items.value.push(item)  // 将新事项添加到items数组中
    saveItems()
    newItem.value = ''
  }
}


//完成数据持久化
  //定义saveItems方法，用于将items数组保存到localStorage中
const saveItems = () => {
  localStorage.setItem('items', JSON.stringify(items.value))
}
  //定义loadItems方法，用于从localStorage中加载items数组
const loadItems = () => {
  //判断localStorage中是否有items数据，有则加载，无则返回空数组
  items.value = JSON.parse(localStorage.getItem('items')?localStorage.getItem('items'):'[]')

}
  //啥时候要加载数据呢？答案是组件挂载时，这个时候就用到onMounted了
onMounted(() => {
  loadItems()
})



//计算已完成事项
//status为true or false的长度
const incompleteItem = computed(() => {
  return items.value.filter(item => item.status).length
})
//计算未完成事项
const completeItem = computed(() => {
  return items.value.filter(item => !item.status).length
})

//清除已完成事项,使用clearCompleted方法
const clearCompleted = () => {
  items.value = items.value.filter(item => !item.status)
  saveItems() //更新数据
}



</script>

<style>
* {
  margin: 0;
  padding: 0;
}

.wrapper {
  width: 500px;
  height: 500px;
  margin: 0 auto;
  padding: 20px;
  background: #e5d6d6;
}
.Title {
  text-align: center;
  font-size: 50px;
}
.todo-list {
  width: 400px;
  height: 70%;
  margin: 0 auto;
  padding: 20px;
  background: white;
}
.Input {
  width: 100%;
  height: 30px;
}


.completed {
  text-decoration: line-through;
}
ul{
  list-style: none;
}
</style>
